package com.lj.tools.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lj.tools.exception.YerException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Objects;


/**
 * 简易HTTP 客户端
 * */
public class HttpSimpleClient {


    public static String get(String path) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(path);
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(httpGet);
            if (response.getCode() != HttpStatus.SC_OK) {
                //异常
                throw new YerException("获取失败" + response.getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            //if (response!=null) response.getEntity().getContent().close();
        }
    }


    public static JSONObject get(String path, JSONObject json) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(path);
        httpGet.addHeader("Content-type", "application/json;charset=UTF-8");

        if(!Objects.isNull(json)){
            httpGet.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8")));
        }
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(httpGet);
            if (response.getCode() != HttpStatus.SC_OK) {
                //异常
                throw new YerException("获取失败" + response.getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            return JSONObject.parseObject(result);
        }finally {
            //if (response!=null) response.getEntity().getContent().close();
        }
    }

    public static <T> T get(String path, JSONObject json, Class<T> cls) throws Exception {
        return get(path, json).toJavaObject(cls);
    }


    public static String post(String url, JSONObject json) throws Exception {
        try{
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type", "application/json;charset=UTF-8");

            if(!Objects.isNull(json)){
                httpPost.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8")));
            }

            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getCode() != HttpStatus.SC_OK) {
                //异常
                throw new YerException("获取失败" + response.getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            String content = EntityUtils.toString(entity);
            //清理
            EntityUtils.consume(entity);
            return content;
        }finally {
        }
    }

    public static JSONObject postFile(String url, JSONObject json, File file) throws Exception {
        try{
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type", "application/json;charset=UTF-8");

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file);
            if(!Objects.isNull(json)){
                json.keySet().stream().forEach( key ->{
                    builder.addTextBody(key, json.getString(key));
                });
            }
            httpPost.setEntity(builder.build());

            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getCode() != HttpStatus.SC_OK) {
                //异常
                throw new YerException("获取失败" + response.getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            String content = EntityUtils.toString(entity);
            //清理
            EntityUtils.consume(entity);
            return JSON.parseObject(content);
        }finally {
        }
    }


    public static byte[] download(String method, String url, JSONObject json) throws Exception{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpUriRequestBase httpGet = null;
        if ("POST".equals(method) || "post".equals(method)){
            httpGet = new HttpPost(url);
        }else{
            httpGet = new HttpGet(url);
        }
        httpGet.addHeader("Content-type", "application/json;charset=UTF-8");
        if(!Objects.isNull(json)){
            httpGet.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8")));
        }
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(httpGet);
            if (response.getCode() != HttpStatus.SC_OK) {
                //异常
                throw new YerException("获取失败" + response.getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            byte[] result = EntityUtils.toByteArray(entity);
            EntityUtils.consume(entity);
            return result;
        }finally {
            //if (response!=null) response.getEntity().getContent().close();
        }
    }

    public static byte[] postDownload(String url, JSONObject json) throws Exception {
        return download("POST", url, json);
    }

    public static byte[] getDownload(String url, JSONObject json) throws Exception {
        return download("GET", url, json);
    }

    public static byte[] postDownload(String url) throws Exception {
        return download("POST", url, null);
    }

    public static byte[] getDownload(String url) throws Exception {
        return download("GET", url, null);
    }

}
